package com.uphone.kingmall.activity.personal;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.china.zhuoyue.R;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.uphone.kingmall.activity.order.AllOrderActivity;
import com.uphone.kingmall.activity.personal.set.AddressListActivity;
import com.uphone.kingmall.app.MyApplication;
import com.uphone.kingmall.base.BaseActivity;
import com.uphone.kingmall.bean.OtherOderBean;
import com.uphone.kingmall.bean.PayAliCallbackBean;
import com.uphone.kingmall.bean.PayResult;
import com.uphone.kingmall.bean.PayWxCallbackBean;
import com.uphone.kingmall.bean.UserAddrBean;
import com.uphone.kingmall.bean.UserDefaultAddr;
import com.uphone.kingmall.listener.onNormalRequestListener;
import com.uphone.kingmall.main.MainActivity;
import com.uphone.kingmall.utils.ActivityCollector;
import com.uphone.kingmall.utils.AppUtil;
import com.uphone.kingmall.utils.CommonUtil;
import com.uphone.kingmall.utils.DialogUtil;
import com.uphone.kingmall.utils.GlideUtils;
import com.uphone.kingmall.utils.GsonUtils;
import com.uphone.kingmall.utils.MyUrl;
import com.uphone.kingmall.utils.OkGoUtils;
import com.uphone.kingmall.utils.intent.IntentData;
import com.uphone.kingmall.view.dialog.RadishDialog;
import com.uphone.kingmall.wxapi.WXPayEntryActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * <pre>
 *     author : radish
 *     e-mail : 15703379121@163.com
 *     time   : 2019/3/20
 *     desc   :
 * </pre>
 */
public class OtherSettleActivity extends BaseActivity {


    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.rl_address)
    RelativeLayout rlAddress;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.iv_goods_image)
    ImageView ivGoodsImage;
    @BindView(R.id.tv_goods_name)
    TextView tvGoodsName;
    @BindView(R.id.tv_order_share)
    TextView tvOrderShare;
    @BindView(R.id.tv_goods_specification)
    TextView tvGoodsSpecification;
    @BindView(R.id.tv_goods_price)
    TextView tvGoodsPrice;
    @BindView(R.id.tv_goods_number)
    TextView tvGoodsNumber;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.rb_ali)
    RadioButton rbAli;
    @BindView(R.id.rb_wchat)
    RadioButton rbWchat;
    @BindView(R.id.rb_union)
    RadioButton rbUnion;
    @BindView(R.id.rb_wallet)
    RadioButton rbWallet;
    @BindView(R.id.rg_pay)
    RadioGroup rgPay;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.tv_home_price)
    TextView tvHomePrice;
    @BindView(R.id.cb_home)
    CheckBox cbHome;
    @BindView(R.id.linear_home)
    LinearLayout linearHome;
    @BindView(R.id.tv_store_price)
    TextView tvStorePrice;
    @BindView(R.id.cb_store)
    CheckBox cbStore;
    @BindView(R.id.tv_logitics_price)
    TextView tvLogiticsPrice;
    @BindView(R.id.cb_logitics)
    CheckBox cbLogitics;
    private OtherOderBean cartBean;
    private int addId = -1;
    private double totalMoney;

    @IntentData
    String jsonStr = "";
    @IntentData
    int id = -1;
    private HttpParams params;
    private RadishDialog payDialog;

    @Override
    public int getLayoutContentId() {
        return R.layout.kingmall_activity_settle_other;
    }

    @Override
    public void initView() {
        CommonUtil.initTitle(this, "结算", ll);

        rgPay.check(R.id.rb_ali);

        cbStore.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                jisuanPrice();
                cbLogitics.setChecked(!b);
                if (b) {
                    cartBean.setPostType(2);
                }
            }
        });
        cbLogitics.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                cbStore.setChecked(!b);
                jisuanPrice();
                if (b) {
                    cartBean.setPostType(1);
                }
            }
        });
        cbHome.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    cartBean.setInstallationType(1);
                } else {
                    cartBean.setInstallationType(0);
                }
                jisuanPrice();
            }
        });
    }

    @Override
    public void initData() {
        LogUtils.e("jsonStr:" + jsonStr);
        if (!TextUtils.isEmpty(jsonStr)) {
            cartBean = GsonUtils.getGson().fromJson(jsonStr, OtherOderBean.class);
            loadData();
        }

        OkGoUtils.normalRequest(MyUrl.getUserDefaultAddr, null, new onNormalRequestListener() {

            @Override
            public void onSuccess(String response, int code) {
                if (code == 0) {
                    UserDefaultAddr bean = GsonUtils.getGson().fromJson(response, UserDefaultAddr.class);
                    if (bean != null && bean.getDefaultAddr() != null) {
                        UserAddrBean defaultAddr = bean.getDefaultAddr();
                        tvName.setText("收货人：" + defaultAddr.getReceiver());
                        tvAddress.setText("收货地址：" + defaultAddr.getRegion() + defaultAddr.getAddress());
                        tvPhone.setText("" + defaultAddr.getTelephone());
                        addId = defaultAddr.getAddrId();
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    private void loadData() {
        if (cartBean != null) {
            tvShopName.setText("" + cartBean.getBean().getGoodsName());
            tvLogiticsPrice.setText("快递：" + cartBean.getBean().getPostFee());
            if (cartBean.getPropBean() != null && cartBean.getPropBean().size() > 0) {
                String goodsPropVal = "";
                for (int i = 0; i < cartBean.getPropBean().size(); i++) {
                    goodsPropVal += cartBean.getPropBean().get(i).getGoodsPropVal() + " ";
                }
                tvGoodsSpecification.setText("规格：" + goodsPropVal);
            } else {
                tvGoodsSpecification.setText("");
            }
            if (cartBean.getInstallationFee() > 0) {
                linearHome.setVisibility(View.VISIBLE);
                tvHomePrice.setText("￥" + cartBean.getInstallationFee());
            } else {
                linearHome.setVisibility(View.GONE);
            }
            tvGoodsPrice.setText("" + cartBean.getPerPrice());
            tvGoodsName.setText("" + cartBean.getBean().getGoodsName());
            tvGoodsNumber.setText("x" + cartBean.getNum());
            GlideUtils.getInstance().loadCornerImage(this, cartBean.getBean().getGoodsMainImg(), SizeUtils.dp2px(2), ivGoodsImage);
            jisuanPrice();
        }
    }

    private void jisuanPrice() {
        BigDecimal totalPrice = new BigDecimal(cartBean.getPerPrice()).multiply(new BigDecimal(cartBean.getNum()));
        totalMoney = totalPrice.doubleValue();
        if (cbLogitics.isChecked()) {
            totalMoney = totalPrice.add(new BigDecimal(cartBean.getBean().getPostFee())).doubleValue();
        }
        if (cbHome.isChecked()) {
            totalMoney = totalPrice.add(new BigDecimal( cartBean.getInstallationFee())).doubleValue();
        }
        tvMoney.setText("¥" + totalMoney);
    }

    @OnClick({R.id.rl_address, R.id.tv_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_address:
                CommonUtil.startIntentType(this, AddressListActivity.class, 1);
                break;
            case R.id.tv_submit:
                submitOrder();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1) {
            if (data != null) {
                UserAddrBean addressBean = (UserAddrBean) data.getSerializableExtra("bean");
                if (addressBean != null) {
                    addId = addressBean.getId();
                    tvName.setText(addressBean.getReceiver() + "");
                    tvAddress.setText("" + addressBean.getRegion() + addressBean.getAddress());
                    tvPhone.setText("" + addressBean.getTelephone());
                }
            }
        }
    }

//    private void getWay(View view) {
//        View inflate = View.inflate(this, R.layout.dialog_settle_way, null);
//        final PopupUtil popupFilter = PopupUtil.getInstance(MyApplication.mContext, inflate);
//        popupFilter.setBasisView(view).showDirection(PopupUtil.Direction.UNDER);
//        inflate.findViewById(R.id.tv_express).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                tvPostFee.setText("快递：" + cartBean.getBean().getPostFee());
//                popupFilter.dismiss();
//            }
//        });
//        inflate.findViewById(R.id.tv_shop).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                tvPostFee.setText("到店");
//                popupFilter.dismiss();
//            }
//        });
//        popupFilter.setDismissListener(new PopupWindow.OnDismissListener() {
//            @Override
//            public void onDismiss() {
//                if (popupFilter != null) {
//                    popupFilter.release();
//                }
//            }
//        });
//    }

    private void submitOrder() {
        if (cartBean != null) {
            if (cbLogitics.isChecked()) {
                if (addId == -1) {
                    ToastUtils.showShort("请填写收货地址");
                    return;
                }
            }
            params = new HttpParams();
            params.put("addrId", addId);
            params.put("postType", cbLogitics.isChecked() ? 1 : 2);
            params.put("installationType", cbHome.isChecked() ? 1 : 0);
            params.put("payType", rgPay.getCheckedRadioButtonId() == R.id.rb_ali ? 1 : (rgPay.getCheckedRadioButtonId() == R.id.rb_wchat ? 2 : 3));
            if (rgPay.getCheckedRadioButtonId() == R.id.rb_wallet) {
                //钱包支付

                payDialog = DialogUtil.showDialogWalletPay(OtherSettleActivity.this, new DialogUtil.OnWalletPayDialogCallBack() {
                    @Override
                    public void callBack(RadishDialog dialog, View view, String psd) {

                        params.put("paypass", psd);

                        submitOrder2();
                    }
                });
//                IntentUtils.getInstance()
//                        .with(this, WalletPayPassActivity.class)
//                        .putString(ConstansUtils.PARA, WalletPayPassActivity.Pay)
//                        .putString("clazz", getClass().getName())
//                        .start();
            } else {
                submitOrder2();
            }

        }

    }

    private void submitOrder2() {
        params.put("remark", etRemark.getText().toString());
        String url = "";
        if (id == -1) {
            params.put("goodsId", cartBean.getBean().getGoodsId());

            if (cartBean.getPropBean() != null) {
                String goodsPropIds = "";
                for (int i = 0; i < cartBean.getPropBean().size(); i++) {
                    goodsPropIds += cartBean.getPropBean().get(i).getGoodsPropId() + ",";
                }
                if (!TextUtils.isEmpty(goodsPropIds)) {
                    String str = goodsPropIds.substring(0, goodsPropIds.length() - 1);
                    params.put("goodsPropId", str);
                }
            }
            params.put("goodsNum", cartBean.getNum());
            url = MyUrl.submitFlashSaleOrder;
        } else {
            params.put("haggleId", id);
            url = MyUrl.submitHaggleOrder;
        }
        params.put("postType", cbLogitics.isChecked() ? 1 : 2);
        params.put("installationType", cbHome.isChecked() ? 1 : 0);
        OkGoUtils.progressRequest(url, this, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                if (code == 1) {
                    //0元支付
                    paySuccess();
                    return;
                }
                if (code != 0) {
                    return;
                }
                try {
                    JSONObject jsonObject = new JSONObject(body);
                    String sign = jsonObject.getString("sign");
                    if (TextUtils.isEmpty(sign)) {
                        paySuccess();
                    } else {
                        if (rgPay.getCheckedRadioButtonId() == R.id.rb_ali) {
                            //支付宝支付
                            alipay(body);
                        } else if (rgPay.getCheckedRadioButtonId() == R.id.rb_wchat) {
                            // 微信支付
                            wxPay(body);
                        } else {
                            // 佣金支付
                            paySuccess();
                        }
                    }
                } catch (JSONException e) {
                    LogUtils.e("异常：" + e.toString());
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    private void wxPay(final String body) {
        AppUtil.checkWchat(this, new AppUtil.AppCheckCallback() {
            @Override
            public void callBack() {
                PayWxCallbackBean bean = GsonUtils.getGson().fromJson(body, PayWxCallbackBean.class);
                PayWxCallbackBean.SignBean sign = bean.getSign();
                PayReq request = new PayReq();
                request.appId = sign.getAppId();
                request.partnerId = sign.getPartnerId();
                request.prepayId = sign.getPrepayId();
                request.packageValue = sign.getPackageValue();
                request.nonceStr = sign.getNonceStr();
                request.timeStamp = sign.getTimeStamp();
                request.sign = sign.getSign();
                WXPayEntryActivity.activity = OtherSettleActivity.this;
                MyApplication.api.sendReq(request);
            }
        });

    }

    @Override
    public void wxPaySuccess() {
        super.wxPaySuccess();
        paySuccess();
    }

    private void paySuccess() {
        if (payDialog != null && payDialog.isShowing()) {
            payDialog.dismiss();
        }
        ActivityCollector.removeAll(MainActivity.class);
        CommonUtil.startIntentType(this, AllOrderActivity.class, 2);
    }

    private void alipay(final String body) {
        AppUtil.checkAli(this, new AppUtil.AppCheckCallback() {
            @Override
            public void callBack() {
                PayAliCallbackBean bean = GsonUtils.getGson().fromJson(body, PayAliCallbackBean.class);
                final String sign = bean.getSign();
                // 必须异步调用
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(OtherSettleActivity.this);
                        final Map<String, String> resultMap = alipay.payV2(sign, true);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                PayResult result = new PayResult(resultMap);
                                String resultStatus = result.getResultStatus();
                                if (TextUtils.equals(resultStatus, "9000")) {
                                    LogUtils.e("handleMessage: 已经支付成功，支付成功");
                                    ToastUtils.showShort("支付成功");
                                    paySuccess();
                                } else if (TextUtils.equals(resultStatus, "6001")) {
                                    LogUtils.e("handleMessage: 已经取消支付");
                                    ToastUtils.showShort("支付取消");
                                } else {
                                    LogUtils.e("handleMessage: 未知状态");
                                    ToastUtils.showShort(resultStatus);
                                }
                            }
                        });
                    }
                }).start();
            }
        });

    }

    @Override
    public void onPayPsdSuccess(String passWord) {
        super.onPayPsdSuccess(passWord);
        params.put("paypass", passWord);

        submitOrder2();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
